package com.itmiaojie.service.impl;

import com.itmiaojie.pojo.LoginUser;
import com.itmiaojie.pojo.ResponseResult;
import com.itmiaojie.pojo.User;
import com.itmiaojie.pojo.UserInfoVo;
import com.itmiaojie.pojo.vo.BlogUserLoginVo;
import com.itmiaojie.service.LoginService;
import com.itmiaojie.utils.BeanCopyUtils;
import com.itmiaojie.utils.JWTUtils;
import com.itmiaojie.utils.RedisCache;
import com.itmiaojie.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Service
@Slf4j
public class LoginServiceImpl implements LoginService {
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private JWTUtils jwtUtils;
    @Autowired
    private RedisCache redisCache;
    @Override
    public ResponseResult login(User user) {
        UsernamePasswordAuthenticationToken
                authenticationToken =
                new UsernamePasswordAuthenticationToken(user.getUserName(),user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        //判断是否认证通过
        if (Objects.isNull(authenticate)) {
            throw new RuntimeException("用户名或密码错误");
        }
        LoginUser loginUser = (LoginUser)authenticate.getPrincipal();
        String id = loginUser.getUser().getId().toString();
        Map<String,Object> map = new HashMap();
        map.put("id",id);
        String token = jwtUtils.getToken(map);
        log.info(token);
        redisCache.setCacheObject("login"+id,loginUser);
        UserInfoVo userInfoVo = BeanCopyUtils.copyBean(loginUser.getUser(), UserInfoVo.class);
        Map<String,String> tokenMap = new HashMap<>();
        tokenMap.put("token",token);
        return ResponseResult.okResult(tokenMap);
    }

    @Override
    public ResponseResult logout() {
        //获取当前登录的用户id
        Long userId = SecurityUtils.getUserId();
        //删除redis中对应的值
        redisCache.deleteObject("login:"+userId);
        return ResponseResult.okResult();
    }
}
